package com.ionehe.group.common.uaa.ex.domain.service.impl;

import com.ionehe.group.common.io.Response;
import com.ionehe.group.common.uaa.ex.application.converter.RoleInfoConvert;
import com.ionehe.group.common.uaa.ex.model.UaaRoleFunction;
import com.ionehe.group.common.uaa.ex.model.UaaRoleInfo;
import com.ionehe.group.common.uaa.ex.model.UaaUserInfo;
import com.ionehe.group.common.uaa.ex.model.UaaUserRole;
import com.ionehe.group.common.uaa.ex.dto.RoleInfoAddDTO;
import com.ionehe.group.common.uaa.ex.dto.RoleInfoUpdateDTO;
import com.ionehe.group.common.uaa.ex.dao.RoleFunctionDao;
import com.ionehe.group.common.uaa.ex.dao.RoleInfoDao;
import com.ionehe.group.common.uaa.ex.dao.UserInfoDao;
import com.ionehe.group.common.uaa.ex.dao.UserRoleDao;
import com.ionehe.group.common.uaa.ex.domain.service.RoleInfoWriteService;
import com.ionehe.group.common.uaa.ex.domain.service.UserCacheWriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @USER:秀
 * @DATE: 2020/11/30
 * @PROJECT_NAME: general-permissions
 * @Description 角色写服务类
 **/
@Service
public class RoleInfoWriteServiceImpl implements RoleInfoWriteService {

    @Autowired(required = false)
    private RoleInfoDao roleInfoDao;

    @Autowired(required = false)
    private RoleFunctionDao roleFunctionDao;

    @Autowired(required = false)
    private UserRoleDao userRoleDao;

    @Autowired(required = false)
    private UserInfoDao userInfoDao;

    @Autowired(required = false)
    private RoleInfoConvert roleInfoConvert;

    @Autowired(required = false)
    private UserCacheWriteService userCacheWriteService;

    @Override
    public Response<Boolean> add(RoleInfoAddDTO roleInfoAddDTO) {
        if (CollectionUtils.isEmpty(roleInfoAddDTO.getFunctionIds())) {
            return Response.no("权限不能为空！");
        }
        UaaRoleInfo roleInfoQuery = new UaaRoleInfo();
        roleInfoQuery.setName(roleInfoAddDTO.getName());
        roleInfoQuery.setCustomerId(roleInfoAddDTO.getCustomerId());
        roleInfoQuery.setIsDelete(false);
        UaaRoleInfo roleInfo = roleInfoDao.selectOne(roleInfoQuery);
        if (roleInfo != null) {
            return Response.no("角色名称不能相同！");
        }
        roleInfo = roleInfoConvert.dto2do(roleInfoAddDTO);
        roleInfo.setCreateTime(new Date());
        roleInfo.setIsDelete(false);
        roleInfoDao.insertSelective(roleInfo);
        Long roleId = roleInfo.getId();
        List<UaaRoleFunction> roleFunctionList = new ArrayList();
        roleInfoAddDTO.getFunctionIds().forEach(functionId -> {
            UaaRoleFunction roleFunction = new UaaRoleFunction();
            roleFunction.setRoleId(roleId);
            roleFunction.setFunctionId(functionId);
            roleFunction.setCreateTime(new Date());
            roleFunctionList.add(roleFunction);
        });
        roleFunctionDao.insertList(roleFunctionList);
        return Response.yes();
    }

    @Override
    public Response<Boolean> update(RoleInfoUpdateDTO roleInfoUpdateDTO) {
        if (CollectionUtils.isEmpty(roleInfoUpdateDTO.getFunctionIds())) {
            return Response.no("权限不能为空！");
        }
        UaaRoleInfo roleInfoQuery = new UaaRoleInfo();
        roleInfoQuery.setId(roleInfoUpdateDTO.getId());
        roleInfoQuery.setIsDelete(false);
        UaaRoleInfo roleInfo = roleInfoDao.selectOne(roleInfoQuery);
        if (roleInfo == null) {
            return Response.no("修改角色id不能为空！");
        }
        //修改角色信息
        roleInfo.setName(roleInfoUpdateDTO.getName());
        roleInfo.setRemark(roleInfoUpdateDTO.getRemark());
        roleInfo.setUpdateTime(new Date());
        roleInfo.setStatus(roleInfoUpdateDTO.getStatus());
        roleInfoDao.updateByPrimaryKeySelective(roleInfo);
        //查询已有角色信息
        UaaRoleFunction roleFunctionQuery = new UaaRoleFunction();
        roleFunctionQuery.setRoleId(roleInfoUpdateDTO.getId());
        List<UaaRoleFunction> roleFunctionList = roleFunctionDao.select(roleFunctionQuery);
        Map<Long, Long> roleFunctionMap = roleFunctionList.stream().collect(Collectors.toMap(UaaRoleFunction::getFunctionId, UaaRoleFunction::getId));
        //已有功能idList
        List<Long> oldFunctionIdList = roleFunctionList.stream().map(UaaRoleFunction::getFunctionId).collect(Collectors.toList());
        //新功能idList
        List<Long> newFunctionIdList = roleInfoUpdateDTO.getFunctionIds();
        //删除功能idList
        List<Long> deleteFunctionIdList = new ArrayList(oldFunctionIdList);
        deleteFunctionIdList.removeAll(newFunctionIdList);
        //新增功能idList
        List<Long> insertFunctionIdList = new ArrayList(newFunctionIdList);
        //dao操作
        insertFunctionIdList.removeAll(oldFunctionIdList);
        if (!CollectionUtils.isEmpty(deleteFunctionIdList)) {
            List<Long> idList = new ArrayList(deleteFunctionIdList.size());
            deleteFunctionIdList.forEach(functionId -> {
                idList.add(roleFunctionMap.get(functionId));
            });
            roleFunctionDao.deleteByIdList(idList);
        }
        if (!CollectionUtils.isEmpty(insertFunctionIdList)) {
            List<UaaRoleFunction> roleFunctionInsertList = new ArrayList(insertFunctionIdList.size());
            insertFunctionIdList.forEach(functionId -> {
                UaaRoleFunction roleFunction = new UaaRoleFunction();
                roleFunction.setRoleId(roleInfoUpdateDTO.getId());
                roleFunction.setFunctionId(functionId);
                roleFunction.setCreateTime(new Date());
                roleFunctionInsertList.add(roleFunction);
            });
            roleFunctionDao.insertList(roleFunctionInsertList);
        }

        // 清除缓存
        List<String> accountList = getAccount(roleInfoUpdateDTO.getId());
        userCacheWriteService.delResourceList(accountList);
        userCacheWriteService.delUser(accountList);
        return Response.yes();
    }

    @Override
    public Response<Boolean> delete(Long id) {
        UaaRoleInfo roleInfo = roleInfoDao.selectByPrimaryKey(id);
        if (roleInfo == null) {
            return Response.no(Response.GENERAL_FAILURE_STATUS, "角色不存在！");
        }
        roleInfoDao.deleteByPrimaryKey(id);
        UaaRoleFunction roleFunctionQuery = new UaaRoleFunction();
        roleFunctionQuery.setRoleId(id);
        roleFunctionDao.delete(roleFunctionQuery);
        UaaUserRole userRole = new UaaUserRole();
        userRole.setRoleId(id);
        userRoleDao.delete(userRole);

        // 清除缓存
        userCacheWriteService.delResourceList(getAccount(id));
        return Response.yes();
    }

    /**
     * 获取roleId绑定的所有用户
     * @param roleId 角色id
     * @return 绑定的所有用户
     */
    private List<String> getAccount(Long roleId) {
        UaaUserRole userRole = new UaaUserRole();
        userRole.setRoleId(roleId);
        List<UaaUserRole> userRoleList = userRoleDao.select(userRole);
        List<Long> userIdList = userRoleList.stream().map(UaaUserRole::getUserId).collect(Collectors.toList());
        List<UaaUserInfo> userInfoList = userInfoDao.selectByIdList(userIdList);
        return userInfoList.stream().map(UaaUserInfo::getPhone).collect(Collectors.toList());
    }
}
